package com.youhui.weixin.utils.weixin;

import com.youhui.weixin.common.exception.MythException;
import com.youhui.weixin.common.info.MythExceptionList;
import okhttp3.*;

import java.io.IOException;

/**
 * Created by https://github.com/kuangcp on 17-10-14  下午7:55
 * HTTP的工具类 GET POST请求
 */
public class HttpUtils {

    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 发起Get请求
     * @param url 地址
     * @return 回复内容 String
     * @throws MythException 异常就表示失败
     */
    public static String get(String url) throws MythException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//            System.out.println(response.body().string());
            return response.body().string();
        } catch (IOException e) {
            throw new MythException(MythExceptionList.REQUEST_FAILED, e, HttpUtils.class);
        }
    }

    public static String post(String url, String jsonParams) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MEDIA_TYPE_JSON, jsonParams))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }
}
